#include "getfile.h"
#include <QDir>
#include <stdio.h>

void getfile(QString fname, bool xpol)
{
  int npts=2*52*96000;
  if(xpol) npts=2*npts;

  qint16* id=(qint16*)malloc(2*npts);
  memset(id,0,2*npts);
  char name[80];
  strcpy(name,fname.toAscii());
  FILE* fp=fopen(name,"rb");

  if(fp != NULL) {
    fread(&datcom_.fcenter,sizeof(datcom_.fcenter),1,fp);
    fread(id,2,npts,fp);
    int j=0;
    for(int i=0; i<npts; i+=2) {
      datcom_.d4[j++]=(float)id[i];
      datcom_.d4[j++]=(float)id[i+1];
      if(!xpol) j+=2;               //Skip over d4(3,x) and d4(4,x)
    }
    fclose(fp);
    datcom_.ndiskdat=1;
    int nfreq=(int)datcom_.fcenter;
    if(nfreq!=144 and nfreq != 432 and nfreq != 1296) datcom_.fcenter=144.125;
    int i0=fname.indexOf(".tf2");
    if(i0<0) i0=fname.indexOf(".iq");
    datcom_.nutc=0;
    if(i0>0) datcom_.nutc=100*fname.mid(i0-4,2).toInt() +
        fname.mid(i0-2,2).toInt();
  }
}

void savetf2(QString fname, bool xpol)
{
  int npts=2*52*96000;
  if(xpol) npts=2*npts;

  qint16* buf=(qint16*)malloc(2*npts);
  char name[80];
  strcpy(name,fname.toAscii());
  FILE* fp=fopen(name,"wb");

  if(fp != NULL) {
    fwrite(&datcom_.fcenter,sizeof(datcom_.fcenter),1,fp);
    int j=0;
    for(int i=0; i<npts; i+=2) {
      buf[i]=(qint16)datcom_.d4[j++];
      buf[i+1]=(qint16)datcom_.d4[j++];
      if(!xpol) j+=2;               //Skip over d4(3,x) and d4(4,x)
    }
    fwrite(buf,2,npts,fp);
    fclose(fp);
  }
  free(buf);
}
